<?php

/*
 * Shortcut to using preg_match and then parsing $matches.  Returns the
 * result in $matches, less the first element, which is the whole string.
 *
 */
function preg_extract($pattern, $subject, $flags=null, $offset=null) {
	$result = preg_match($pattern, $subject, $matches, $flags, $offset);
	if (isset($matches) and is_array($matches)) {
		array_shift($matches);
		return $matches;
	}
	return false;
}

/*
 * Same as above function but using preg_match_all.
 *
 */
function preg_extract_all($pattern, $subject, $flags=null, $offset=null) {
	$result = preg_match_all($pattern, $subject, $matches, $flags, $offset);
	if (isset($matches) and is_array($matches)) {
		array_shift($matches);
		return $matches;
	}
	return false;
}

/*
 * array_index - Reindex an array of arrays, using a value of the 
 * sub array as the key.
 * 
 * array array_index ( array $array, string $key )
 *
 */
function array_index($array, $key) {
        $new_array = array();
        foreach ($array as $element) {
                $new_array[$element[$key]] = $element;
        }
        return $new_array;
}

/*
 * human_filesize - Take a size in bytes, and return a human
 * readable version.
 * 
 * string human_filesize( int filesize )
 *
 */
function human_filesize($size) {
	$filesizename = array(" Bytes", " KB", " MB", " GB", " TB", " PB", " EB", " ZB", " YB");
	return round($size/pow(1024, ($i = floor(log($size, 1024)))), 2) . $filesizename[$i];
}

/*
 * famfamfam_icon - take a filename as input and output a 
 * suitable famfamfam icon.
 *
 */
function famfamfam_icon($filename) {
	$extension = strtolower(preg_replace('/^.*\./', '', $filename));
	$icons = array(
		'arw'  => 'camera',
		'cr2'  => 'camera',
		'dmg'  => 'cd',
		'dng'  => 'camera',
		'doc'  => 'page_white_word',
		'docx' => 'page_white_word',
		'gif'  => 'photo',
		'iso'  => 'cd',
		'jpeg' => 'photo',
		'jpg'  => 'photo',
		'pdf'  => 'page_white_acrobat',
		'php'  => 'page_white_php',
		'png'  => 'photo',
		'psd'  => 'picture',
		'rb'   => 'page_white_ruby',
		'txt'  => 'page_white_text',
		'xls'  => 'page_white_excel',
		'xlsx' => 'page_white_excel',
		'zip'  => 'photo'
	);
	if ($icons[$extension]) return $icons[$extension];
	else return 'page_white';

}

/*
 * highlight - take a haystack and needle, and wrap
 * instances of needle in <span class="hl"></span>
 *
 */
function highlight($haystack, $needle) {
	if ($needle) return preg_replace("/(".$needle.")/i", "<span class='hl'>$1</span>", $haystack);
	else return $haystack;
}

/*
 * make_path - take any string, and turn it into one suitable
 * to be used in a url
 *
 */
function make_path($string) {
	// deal with letters with accents
	$accents = array(
		'À' => 'a', 'Á' => 'a', 'Â' => 'a', 'Ã' => 'a', 'Ä' => 'a', 'Å' => 'a', 
		'Æ' => 'a', 'Ç' => 'c', 'È' => 'e', 'É' => 'e', 'Ê' => 'e', 'Ë' => 'e', 
		'Ì' => 'i', 'Í' => 'i', 'Î' => 'i', 'Ï' => 'i', 'Ð' => 'd', 'Ñ' => 'n', 
		'Ò' => 'o', 'Ó' => 'o', 'Ô' => 'o', 'Õ' => 'o', 'Ö' => 'o', 'Ø' => 'o', 
		'Ù' => 'u', 'Ú' => 'u', 'Û' => 'u', 'Ü' => 'u', 'Ý' => 'y', 'Þ' => 'b', 
		'ß' => 's', 'à' => 'a', 'á' => 'a', 'â' => 'a', 'ã' => 'a', 'ä' => 'a', 
		'å' => 'a', 'æ' => 'a', 'ç' => 'c', 'è' => 'e', 'é' => 'e', 'ê' => 'e', 
		'ë' => 'e', 'ì' => 'i', 'í' => 'i', 'î' => 'i', 'ï' => 'i', 'ð' => 'd', 
		'ñ' => 'n', 'ò' => 'o', 'ó' => 'o', 'ô' => 'o', 'õ' => 'o', 'ö' => 'o', 
		'ø' => 'o', 'ù' => 'u', 'ú' => 'u', 'û' => 'u', 'ý' => 'y', 'ý' => 'y', 
		'þ' => 'b', 'ÿ' => 'y', 'Ŕ' => 'R', 'ŕ' => 'r', 'ā' => 'a', 'ī' => 'i', 
		'ž' => 'z', 'ž' => 'z', 'č' => 'c', 'č' => 'c', 'š' => 's', 'š' => 's', 
		'è' => 'e', 'è' => 'e', 'ě' => 'e', 'ě' => 'e', 'ô' => 'o', 'ǫ' => 'o', 
		'ę' => 'e', 'ü' => 'u'
	);
	foreach($accents as $k => $v) {
		$string = str_replace($k, $v, $string);
	}
	
	// lowercase
	$string = strtolower($string);
	
	// replace & character with "and"
	$string = str_replace('&', "and", $string);
	
	// replace spaces with -
	$string = preg_replace("/ /", "-", $string);
	
	// strip out anything that isn't an acceptable character
	$string = preg_replace('/[^a-z0-9-_]/', '', $string);
	
	// get rid of any hyphen at the start/end
	$string = trim($string, '-');
	
	// multiple hyphens together should be single
	$string = preg_replace('/-+/', '-', $string);
	
	// and return.
	return $string;
	
}

/*
 * array_flatten - given an array of arrays, reduce to a single 
 * array containing all values.
 *
 */
function array_flatten($array) {
	$array_found = false;
	$array = array_values($array);
	for($i=0;$i<count($array);$i++) {
		if (is_array($array[$i])) {
			$array = array_merge(
				array_slice($array, 0, $i),
				array_flatten($array[$i]),
				array_slice($array, $i+1)
			);
			$array_found = true;
			break;
		}
	}

	if ($array_found) return array_flatten($array);
	return $array;
}

/*
 * Get the last query details from the zend profiler, and reconstruct 
 * the SQL it used.
 *
 */
function zend_db_last_query() {
	global $db;
	$prof = $db->getProfiler()->getLastQueryProfile();
	$query  = $prof->getQuery();
	$params = $prof->getQueryParams();
	foreach($params as $param) {
		if (is_numeric($param)) {
			$query = preg_replace('/\?/', $param, $query, 1);
		} else {
			$query = preg_replace('/\?/', "'" . addslashes($param) . "'", $query, 1);
		}
	}
	return $query;
}

/*
 * 
 *
 */
function parse_plugin($file, $configured) {
	global $app_root;
	$detail       = array('file' => substr($file, strlen($app_root)));
	$file_content = file_get_contents($file);
	$matches      = preg_extract('/^<\?php\n(\/\*.*)\*\//s', $file_content);
	$lines        = preg_split("/[\n\r]/", $matches[0]);
	$config       = array();
	foreach($lines as $line) {
		$line = preg_replace('/^.*\* */', '', $line);
		$item = preg_split('/ *: */', $line, 2);
		if (isset($item[0]) and isset($item[1])) $detail[$item[0]] = $item[1];
	}
	if ($detail['enabled'] = isset($configured[$detail['file']])) {
		$detail['config'] = $configured[$detail['file']]['config'];
		if (isset($configured[$detail['file']]['manage_path'])) $detail['manage_path'] = $configured[$detail['file']]['manage_path'];
	}
	return $detail;
}
